<template>
  <div id="centerLeft2">
    <div class="bg-color-black">
      <div class="d-flex pt-2 pl-2" >
        <span>
          <icon name="align-left" class="text-icon"></icon>
        </span>
        <span class="fs-xl text mx-2">技术问题关联</span>
      </div>
      <!-- 全屏按钮 -->
      <!--    <button class="fullscreen-btn" @click="toggleFullscreen">-->
      <!--      <span v-if="!isFullscreen">⛶</span>-->
      <!--      <span v-else>⨉</span>-->
      <!--    </button>-->
      <div class="body-box">
        <div class="dv-cap-chart" id="chart-container" :key="chartKey"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import * as XLSX from 'xlsx';
import xlsxFile from '../assets/data/data.xlsx'; // 通过 webpack 引入

export default {
  name: 'TechGraphChart',
  data() {
    return {
      isFullscreen: false,
      chart: null,
      chartKey: 0,
      graphData: null
    };
  },
  mounted() {
    this.fetchData();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.chart) this.chart.dispose();
  },
  methods: {
    async fetchData() {
      try {
        const response = await fetch(xlsxFile);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const arrayBuffer = await response.arrayBuffer();
        const workbook = XLSX.read(arrayBuffer, { type: 'array' });

        const sheetName = '技术问题';
        const worksheet = workbook.Sheets[sheetName];
        if (!worksheet) {
          throw new Error('找不到工作表: 技术问题');
        }

        const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

        const nodesSet = new Set();
        const nodes = [];
        const links = [];

        for (let i = 1; i < data.length; i++) {
          const techNode = data[i][0];
          const problemNode = data[i][1];
          const value = parseFloat(data[i][2]);

          // 只创建非空节点
          if (techNode && !nodesSet.has(techNode)) {
            nodesSet.add(techNode);
            nodes.push({ name: techNode, type: '技术' });
          }

          if (problemNode && !nodesSet.has(problemNode)) {
            nodesSet.add(problemNode);
            nodes.push({ name: problemNode, type: '问题' });
          }

          // 只有技术和问题都存在才生成连线
          if (techNode && problemNode) {
            links.push({
              source: techNode,
              target: problemNode,
              value,
              sourceName: techNode,
              targetName: problemNode
            });
          }
        }
        this.graphData = { nodes, links };

        this.initChart();
      } catch (error) {
        console.error('读取文件时出错:', error);
      }
    },

    initChart() {
      const chartDom = document.getElementById('chart-container');
      if (!chartDom) return;

      if (this.chart) this.chart.dispose();
      this.chart = echarts.init(chartDom);
      // 🔑 将技术节点排在前，问题节点排在后
      const techNodes = this.graphData.nodes.filter(n => n.type === '技术');
      const problemNodes = this.graphData.nodes.filter(n => n.type === '问题');
      const orderedNodes = [...techNodes, ...problemNodes];
      const option = {
        tooltip: {
          formatter: function(params) {
            if (params.dataType === 'edge') {
              return `${params.data.sourceName} → ${params.data.targetName}<br>权重: ${params.data.value.toFixed(5)}`;
            }
            return `${params.name}`;
          }
        },
        series: [
          {
            type: 'graph',
            layout: 'circular',
            data: orderedNodes.map(n => ({
              ...n,
              symbolSize: 60,
              itemStyle: { color: n.type === '技术' ? '#43BC86' : 'red' },
              label: { show: true }
            })),
            links: this.graphData.links,
            roam: true,
            label: { show: true, color: '#fff', fontSize: 16 },
            lineStyle: { color: '#aaa', curveness: 0.5, width: 2 },
            edgeSymbol: ['none', 'arrow'],
            edgeSymbolSize: [0, 8]
          }
        ]
      };

      this.chart.setOption(option);
    },

    handleResize() {
      if (this.chart) this.chart.resize();
    },

    toggleFullscreen() {
      this.isFullscreen = !this.isFullscreen;
      this.chartKey += 1;
      this.$nextTick(() => {
        if (this.chart) this.chart.dispose();
        this.initChart();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
$box-height: 370px;
$box-width: 510px;

#centerLeft2 {
  padding: 10px;
  height: $box-height;
  width: $box-width;
  border-radius: 5px;
  .bg-color-black {
    padding: 5px;
    height: $box-height - 10px;
    //width: $box-width;
    border-radius: 10px;
  }
  .text {
    color: #c3cbde;
    font-size: 20px;
  }
  .body-box {
    border-radius: 10px;
    overflow: hidden;
    .dv-cap-chart {
      width: 100%;
      height: 320px;
    }
  }
}
</style>
